<?php
namespace Auth\Controller;
use Todo\Controller\ApiController;
use Todo\Service\LoginService;
use Todo\Service\TokenService;

class LoginController extends ApiController {

    /**
     * 登录验证
     */
    public function index(){
        if(IS_POST)
        {
            $account = I('post.account');
            $password = I('post.password');
            if(!$account || !$password) $this->apiError('账号或密码不能为空');

            $ret = LoginService::getInstance()->doLogin($account, $password);
            if(!$ret){
                $this->apiError('登录失败!'. LoginService::getInstance()->getError());
            }

            $back = session('__back');
            if(!$back) $back = C('AUTH.BACK');

            $this->apiSuccess( '验证成功!', $back);
        }
    }

    /**
     * 验证账号密码，并返回令牌
     */
    public function token(){
        $account = I('post.account');
        $password = I('post.password');
        if(!$account || !$password) $this->apiError('账号或密码不能为空');

        $token = LoginService::getInstance()->loginToken($account, $password);
        if(!$token){
            $this->apiError('登录失败!'. LoginService::getInstance()->getError());
        }
        $this->apiData(array('token'=>$token['code'], 'expired_time'=>strtotime($token['expired_time'])), '登录成功!');
    }

    /**
     * 返回用户信息，过滤敏感数据
     * @param array $userInfo 用户详细信息
     * @param array $terminalInfo 用户所在终端的信息
     */
    protected function _returnUser($userInfo, $terminalInfo){

        unset($userInfo['id'],$userInfo['password'],$userInfo['moblie'],$userInfo['email'],$userInfo['terminal_id']);
        unset($userInfo['is_del'],$userInfo['status'],$userInfo['is_super'],$userInfo['salt']);
        $userInfo['theme'] = $terminalInfo['theme'];
        $userInfo['title'] = $terminalInfo['title'];
        $userInfo['terminal'] = $terminalInfo['code'];

        $this->apiSuccess('登录成功!', $userInfo);
    }
}